package com.example.shirospringboottest.shiro;

import com.example.shirospringboottest.pojo.User;
import com.example.shirospringboottest.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("MyRealm.doGetAuthenticationInfo --->进入授权");

        System.out.println("authenticationToken = " + authenticationToken);

        if(authenticationToken.getPrincipal() == null){
            return null;
        }

        String userName = authenticationToken.getPrincipal().toString();

        User user = new User();

        user.setUserName(userName);

        User userInDB = this.loginService.login(user);

        if(userInDB == null){
            //此方法返回null，shiro底层抛出UnknownAccountException
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(

                userInDB,
                userInDB.getPassword(),
                ByteSource.Util.bytes(userInDB.getSalt()),
                "userReal"

        );

        return simpleAuthenticationInfo;
    }
}
